<template>
  <div class>
    <el-form ref="elasticsearchBulk" :model="elasticsearchBulk" label-width="190px" size="mini">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="elasticsearchBulk.name"></el-input>
      </el-form-item>
      <el-tabs v-model="tabsValue" type="border-card">
        <el-tab-pane label="文件" name="General">
          <div class="box" title="索引" style="margin-top:20px;">
            <el-form-item label="数据源:" prop="name">
              <el-popover
                ref="datasourceListPopover"
                placement="bottom-start"
                trigger="click"
                v-model="srcPopover">
                <table-tree ref="datasourceListTree" @srcSelectHandler="srcSelectHandler"
                            @tableSelectHandler="tableSelectHandler"
                            style="height: 400px; overflow-y: auto"></table-tree>
                <el-input v-model="name" slot="reference"  placeholder="点击选择数据源"></el-input>
              </el-popover>
            </el-form-item>
            <el-form-item label="数据表:" prop="index">
              <el-select v-model="elasticsearchBulk.general.index" allow-create placeholder="请选择" filterable style="width: 90%">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

          </div>
          <div class="box" title="选项" style="margin-top:20px;">
            <el-form-item label="批次大小" prop="batchSize">
              <el-input v-model="elasticsearchBulk.general.batchSize"></el-input>
            </el-form-item>
            <el-form-item label="遇到错误是否终止" prop="stopOnError">
              <el-checkbox v-model="elasticsearchBulk.general.stopOnError" true-label="Y" false-label="N"></el-checkbox>
            </el-form-item>
            <el-form-item label="批次写入超时时间" prop="timeoutUnit" v-if="false">
              <el-row>
                <el-col :span="12">
                  <el-input v-model="elasticsearchBulk.general.timeoutUnit"></el-input>
                </el-col>
                <el-col :span="12">
                  <el-select
                    v-model="elasticsearchBulk.general.jsonField"
                    filterable
                    placeholder="请选择"
                    @focus="getvalueFormats"
                    style="width:100%"
                  >
                    <el-option
                      v-for="item in formatOptions"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="ID字段" prop="idField">
              <el-select
                v-model="elasticsearchBulk.general.idField"
                filterable
                placeholder="请选择"
                @focus="getvalueFormats"
                style="width:100%"
              >
                <el-option
                  v-for="item in fieldColumns"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="存在是否覆盖" prop="overwriteIfExists">
              <el-checkbox v-model="elasticsearchBulk.general.overwriteIfExists" true-label="Y" false-label="N"></el-checkbox>
            </el-form-item>
            <el-form-item label="输出行" prop="useOutput">
              <el-checkbox v-model="elasticsearchBulk.general.useOutput" true-label="Y" false-label="N"></el-checkbox>
            </el-form-item>
            <el-form-item label="ID输出字段" prop="idOutputField">
              <el-input v-model="elasticsearchBulk.general.idOutputField" :disabled="!useOutput"></el-input>
            </el-form-item>
            <el-form-item label="JSON输入" prop="isJson">
              <el-checkbox v-model="elasticsearchBulk.general.isJson" true-label="Y" false-label="N"></el-checkbox>
            </el-form-item>
            <el-form-item label="JSON字段" prop="jsonField">
              <el-select
                v-model="elasticsearchBulk.general.jsonField"
                filterable
                @focus="getvalueFormats"
                style="width:100%"
                :disabled="!isJson"
              >
                <el-option
                  v-for="item in fieldColumns"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-tab-pane>
        <el-tab-pane label="字段" name="fields">
          <template>
            <el-table :data="elasticsearchBulk.fields" border
                      style="width: 100%;"  size="mini" id="fields"
                      @getStreamFieldOptions="getStreamFieldsOptions" ref="fields"
                      :height="domHeight - 350 + 'px'">
              <el-table-column label="操作" width="80" :resizable=false>
                <template slot-scope="scope">
                  <div class="optionStyle">
                    <el-button
                      type="text"
                      @click="removeFields"
                      size="mini">移除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                type="index"
                width="50" label="序号">
              </el-table-column>
              <el-table-column property="columnName" label="名称" >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.columnName"
                             placeholder="请选择字段" size="mini" style="width: 100%">
                    <el-option v-for="column in fieldColumns"
                               :key="column.name"
                               :prop="column.name"
                               :label="column.name"
                               :value="column.name">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column property="targetName" label="目标名称" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.targetName" size="mini"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex">
              <el-button class="el-table-add-row" icon="el-icon-plus" @click="addFields">添加</el-button>
              <div style="width: 20px;"></div>
              <el-button class="el-table-add-row" icon="el-icon-thumb" @click="getField">获取字段</el-button>
              <!--<div style="width: 20px;"></div>-->
              <el-button class="el-table-add-row" v-if="false">最小宽度</el-button>
            </el-row>
          </template>
        </el-tab-pane>
        <el-tab-pane label="设置" name="settings">
          <template>
            <el-table :data="elasticsearchBulk.settings" border style="width: 100%;"  size="mini" id="settings" @getStreamFieldOptions="getStreamSettingsOptions" ref="settings">
              <el-table-column label="操作" width="80" :resizable=false>
                <template slot-scope="scope">
                  <div class="optionStyle">
                    <el-button
                      type="text"
                      @click="removeSettings"
                      size="mini">移除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column property="Setting" label="设置">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.Setting" size="mini"></el-input>
                </template>
              </el-table-column>
              <el-table-column property="Value" label="值" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.Value" size="mini"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex">
              <el-button class="el-table-add-row" icon="el-icon-plus" @click="addSettings">添加</el-button>
            </el-row>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button type="success" icon="el-icon-view" v-if="false">预览</el-button>
         <el-button
           icon="el-icon-back"
           @click="cancel">取消
            </el-button>
            <el-button
              type="primary" icon="el-icon-check"
              @click="handleSaveData()">确定
           </el-button>
      </span>
    </div>
  </div>
</template>
<script>
  import API from '../../../../../api/index'
import mxgraph from '../../../../../graph/VueMxGraphLoader'
import tableTree from '../../../table/table-tree.vue'
/* eslint-disable new-cap */
const { mxUtils, mxCodec } = mxgraph

  export default {
    name: 'elasticsearchBulk',
    props: {
      name: String
    },
    components: {
      tableTree
    },
    computed: {
      domHeight: {
        get () {
          return this.$store.state.common.documentClientHeight - this.$BODY_MARGIN - 60
        }
      }
    },
    watch: {
      'elasticsearchBulk.general.useOutput': function (val, oldvlaue) {
        const flag = val === 'Y'
        this.useOutput = flag
      },
      'elasticsearchBulk.general.isJson': function (val, oldvlaue) {
        const flag = val === 'Y'
        this.isJson = flag
      }
    },
    data () {
      return {
        name: '',
        tabsValue: 'General',
        graph: null,
        srcPopover: false,
        useOutput: false,
        isJson: false,
        elasticsearchBulk: {
          name: '',
          general: {
            hostId: '',
            index: '',
            batchSize: '50000',
            timeout: null,
            timeoutUnit: 'SECONDS',
            type: '',
            isJson: false,
            jsonField: '',
            idField: '',
            overwriteIfExists: false,
            idOutputField: null,
            useOutput: false,
            stopOnError: true
          },
          fields: [],
          servers: [],
          settings: []
        },
        temp: {
          name: '',
          general: {
            hostId: '',
            index: '',
            batchSize: '50000',
            timeout: null,
            timeoutUnit: 'SECONDS',
            type: '',
            isJson: false,
            jsonField: '',
            idField: '',
            overwriteIfExists: false,
            idOutputField: null,
            useOutput: false,
            stopOnError: true
          },
          fields: [],
          servers: [],
          settings: []
        },
        tempElasticsearchBulk: null,
        fieldColumns: []
      }
    },
    methods: {
      loadData (data) {
        if (data) {
          this.$forceUpdate()
          this.elasticsearchBulk = Object.assign({}, data)
          this.tempElasticsearchBulk = Object.assign({}, data)
        // 返回数据源id
          if (data.general.hostId) {
            const _this = this
            window.setTimeout(function () {
              _this.$nextTick(() => {
                _this.name = _this.$refs.datasourceListTree.getName(data.general.hostId)
              })
            }, 1000)
          }
        }
      },
      // 保存表单数据
      handleSaveData () {
        this.$emit('savePluginData', this.elasticsearchBulk)
      },
      cancel () {
        if (this.tempElasticsearchBulk) {
          this.saveTempPluginData(this.tempElasticsearchBulk)
        } else {
          let tempdata = JSON.parse(JSON.stringify(this.temp))
          tempdata['name'] = this.elasticsearchBulk.name
          this.saveTempPluginData(tempdata)
        }
        this.$emit('cancel')
      },
      setGraph (val) {
        this.graph = val
        this.getField()
      },
      // 重置表单数据
      resetFormData (stepname) {
        this.$forceUpdate()
        this.$refs['elasticsearchBulk'].resetFields()
        this.elasticsearchBulk = JSON.parse(JSON.stringify(this.temp))
        this.elasticsearchBulk.name = stepname
      },
      setChildSuffix () {
        this.$refs.filepro.setSuffix('csv')
      },

      // 获取关键字段
      async getField () {
        this.elasticsearchBulk.fields = []
        const value = await this.getXml()
        if (this.elasticsearchBulk.name) {
          API.trans.inputFields(value, {'stepName': this.elasticsearchBulk.name}).then(res => {
            if (res.data) {
              this.fieldColumns = res.data
              for (var i = 0; i < res.data.length; i++) {
                this.elasticsearchBulk.fields.push({ columnName: res.data[i].name, targetName: res.data[i].name })
              }
            } else {
              this.fieldColumns = []
              this.elasticsearchBulk.fields = []
            }
          })
        }
      },

      saveTempPluginData (formData) {
        this.$emit('saveTempPluginData', formData)
      },
      getXml () {
        this.saveTempPluginData(this.elasticsearchBulk)
        const graph = this.graph
        const enc = new mxCodec(mxUtils.createXmlDocument())
        const node = enc.encode(graph.getModel())
        const value = mxUtils.getPrettyXml(node)
        return value
      },
      async getStreamField () {
        const value = await this.getXml()
        if (this.elasticsearchBulk.name) {
          return API.trans.inputFields(value, { stepName: this.elasticsearchBulk.name })
        }
      },
      // 字段添加行
      addFields () {
        this.elasticsearchBulk.fields.push({})
        this.$nextTick(() => {
          let container = this.$el.querySelector('#fields > .el-table__body-wrapper')
          container.scrollTop = container.scrollHeight
        })
      },
      // 字段删除行
      removeFields (index) {
        this.elasticsearchBulk.fields.splice(index, 1)
      },
      async getStreamFieldsOptions () {
        const result = this.getStreamField()
        this.$refs['fields'].setOptions(result)
      },
      // 设置添加行
      addSettings () {
        this.elasticsearchBulk.settings.push({})
        this.$nextTick(() => {
          let container = this.$el.querySelector('#settings > .el-table__body-wrapper')
          container.scrollTop = container.scrollHeight
        })
      },
      // 设置删除行
      removeSettings (index) {
        this.elasticsearchBulk.settings.splice(index, 1)
      },
      async getStreamSettingsOptions () {
        const result = this.getStreamField()
        this.$refs['settings'].setOptions(result)
      },
      srcSelectHandler (data, node) {
        this.elasticsearchBulk.general.index = data.name
        this.$http({
          url: this.$http.adornUrl(`/src/source/info/${data.id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.elasticsearchBulk.general.hostId = data.entity.id
            this.name = data.entity.name
            this.elasticsearchBulk.servers = []
            var connection = {
              address: data.entity.ip,
              port: data.entity.port
            }
            this.elasticsearchBulk.servers.push(connection)
          }
        })
      },
      /***
       * 表选中
       * @param data
       * @param node
       */
      tableSelectHandler (data, node) {
        this.elasticsearchBulk.general.index = data.name
        this.$http({
          url: this.$http.adornUrl(`/src/source/info/${node.parent.data.id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.elasticsearchBulk.general.hostId = data.entity.id
            this.name = data.entity.name
            this.elasticsearchBulk.servers = []
            var connection = {
              address: data.entity.ip,
              port: data.entity.port
            }
            this.elasticsearchBulk.servers.push(connection)
          }
        })
        this.srcPopover = false
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .el-form-item {
    margin-bottom: 10px !important;
  }
  .divBut {
    text-align: center;
    margin-top: 54px !important;
  }
  .button {
    width: 80px;
    height: 40px;
    display: inline-block;
    margin-left: 10px;
    margin-top: 5px;
  }
  .el-tabs >>> .el-tabs__content {
    padding: 15px !important;
  }
  .el-dialog__footer {
    margin-top: 10px;
  }
  .box{
    position:relative;
    border:1px solid #dcdfe6;
    padding:30px 5px 10px 5px;
  }
  .box::before{
    content:attr(title);
    position:absolute;
    top: 0%;
    left:10%;
    transform:translateX(-50%);
    -webkit-transform:translate(-50%,-50%);
    padding:0px 10px;
    background-color:#fff;
  }
</style>
